<div class="page-wrapper">

    <div class="header">
        <div class="title">订单列表</div>
    </div>

    <div class="order-list-body">
        <div id="ongoing-orders-list" class="ongoing-orders" style="display: none;">
            <div class="status"><div class="text">进行中</div></div>
            <div class="h-line"><hr></div>
        </div>
        <div id="history-orders-list" class="orders-list" style="display: none;">
            <div class="status"><div class="text">已结单</div></div>
            <div class="h-line"><hr></div>
        </div>

        <div id="repeat-history-item" class="group" style="display: none;">

            <i class="stamp icon-stamporderclear"></i>
            <div class="des">
                <div class="left store">南京大排档</div>
                <div class="right top-level"><i class="remove icon-remove"></i></div>
            </div>
            <div class="prop">
                <div class="number">订单编号：<span class="text">22</span></div>
                <div class="line">
                    <div class="time">下单时间：<span class="text">2016-9-8 13:42:22</span></div>
                    <div class="table">就餐桌号：<span class="text">静女</span></div>
                </div>
            </div>
            <div class="summary">
                <div class="left total">消费总计:<span class="money">￥328</span></div>
                <div class="right">已结单</div>
            </div>
        </div>

        <div id="repeat-ongoing-item" class="group" style="display: none;">
            <div class="des">
                <div class="left store">南京大排档</div>
                <div class="right time">2016-09-08 10:53</div>
            </div>
            <div class="prop">
                <div class="number">订单编号：<span class="text">22</span></div>
                <div class="people">就餐人数：<span class="text">5人</span></div>
                <div class="table">就餐桌号：<span class="text">丐帮</span></div>
            </div>
            <div class="summary">
                <div class="left total">消费总计:<span class="money unpayed">￥328</span></div>
                <button class="right btn btn-buy">买单</button>
            </div>
        </div>
        <div id="orders-list-err" class="error" style="display: none;"><div class="text">未获取到订单^$$^</div></div>
    </div>
    <script>
        (function(){
            'use strict';
            var storeName = '';

            var pageable = {
                page:0
            };

            var $ongoingList = $('#ongoing-orders-list');
            var $historyList = $('#history-orders-list');
            var $repeatHistoryItem = $('#repeat-history-item');
            var $repeatOngoingItem = $('#repeat-ongoing-item');

            loadData();

            spa.addResumeCallback(function(){
                refresh();
            });

            function reset() {
                $ongoingList.hide();
                $historyList.hide();
                $ongoingList.children('.group').remove();
                $historyList.children('.group').remove();
            }

            function refresh() {
                console.log('refresh');
                reset();
                loadData();
            }

            function loadData(){
                console.log(window.tableId);
                if(window.tableId){

                    //获取未审核订单
                    $.get('/wechatOrder/api/getCurrentTableNoConfirmOrder/'+window.tableId,'',function(data){
                        console.log(data);

                        if(data){
                            showOrders(data)
                        }
                        showNoOrders();

                    });

                    $.get('/wechatOrder/api/getCurrentTableOrder/'+window.tableId,'',function(data){
                        console.log(data);
                        if(data){
                            showOrders(data)
                        }
                        showNoOrders();
                    });
                }else{

                }
                $.get('/wechatOrder/api/getUserHistoryOrder/'+ window.userId + '/'+pageable.page,function (data) {
                    if(data){
                        var orders = data.result;

                        console.log(data);
                        if(orders && orders.length > 0){
                            showOrders(orders);
                        }
                        showNoOrders();
                    }else{
                    }
                });
            }

            function showNoOrders(){
                if($ongoingList.children('.group').length == 0 && $historyList.children('.group').length == 0){
                    console.log('shownoOrders');
                    $ongoingList.hide();
                    $historyList.hide();
                    $('#orders-list-err').show();
                }else{
                    $('#orders-list-err').hide();
                }
            }

            function showOrders(orders) {
                $(orders).each(function (i,item) {
                    if(item.state == OrderState.confirmed || item.state == OrderState.unconfirmed){
                        showUnpayedItem(item);
                    }else{
                        if($historyList.is(':hidden')){
                            $historyList.show();
                        }
                        showHistoryItem(item);
                    }
                });
            }

            function showUnpayedItem(item) {
                if($ongoingList.is(':hidden')){
                    $ongoingList.show();
                }
                var $item = cloneOngoingItem();
                $item.find('.store').text(item.storeName);
                var time  = item.createDate;
                $item.find('.time').text(time);
                $item.attr('order-id',item.orderId);
                $item.find('.number .text').text(item.orderId);
                $item.find('.people .text').text(item.people);
                $item.find('.total .money').text('￥'+common.fixOne(item.price));
                $item.find('.table .text').text(item.tableName);
                if(item.state == OrderState.unconfirmed){
                    $item.find('.btn-buy').text('审核中...');
                }else{
                    $item.click(showDetail);
                }
//                $item.find('.btn-buy').click(buyClicked);

                $ongoingList.append($item);
            }

//            function buyClicked(){
//                var $group = $(this).parents('.group');
//                var orderId = $group.attr('order-id');
//                //买单
//                console.log(orderId);
//                callpay();
//                return false;
//            }

            function callpay()
            {
                if (typeof WeixinJSBridge == "undefined"){
                    if( document.addEventListener ){
                        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
                    }else if (document.attachEvent){
                        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
                    }
                }else{
                    jsApiCall();
                }
            }

            function jsApiCall(){
                var loadInfo = common.showLoading("加载中，请稍后...");
                $.ajax({
                    type:"GET",
                    url:"/wechat/payOrder?rank="+Math.random(),
                    dataType:"json",
                    timeout: 10000,
                    success: function(data){
                        common.dismissLoading(loadInfo);
                        if(data!=null){
                            WeixinJSBridge.invoke(
                                    'getBrandWCPayRequest',
                                    data,
                                    function(res){
                                        if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                                            refresh();
                                        }else if(res.err_msg == "get_brand_wcpay_request:cancel"){

                                        }
                                        else{
                                            alert("支付订单失败");
                                        }

                                    }
                            );
                        }else{
                            alert("支付数据异常。");
                        }
                    },
                    error:function(e){
                        common.dismissLoading(loadInfo.remove());
                        alert("支付数据异常。")
                    }
                });
            }

            function showHistoryItem(item) {
                var $item = cloneHistoryItem();
                $item.find('.store').text(item.storeName);
                var time  = item.createDate;
                $item.find('.number .text').text(item.orderId);
                $item.find('.time .text').text(time);
                $item.find('.total .money').text('￥'+item.price);
                $item.find('.table .text').text(item.tableName);
                $item.find('.total .right').text(item.state == 1? '已结单':'已取消');
                $item.find('.remove').click(removeClicked);
                $item.click(showDetail);
                $item.attr('order-id',item.orderId);
                $historyList.append($item);
            }

            function showDetail(){
                var orderId = $(this).attr('order-id');
                location.href="#action=order&orderId=" + orderId;
            }


            function removeClicked(){
                if(confirm('确定删除订单?')){
                    var $group = $(this).parents('.group');
                    var orderId = $group.attr('order-id');
                    var $floatUI = common.showLoading('删除中...');
                    var url = '/wechatOrder/api/deleteOrder/' + orderId;
                    $.get(url,'',function (data) {
                        common.dismissLoading($floatUI);
                        if(data && data.status == 'success'){
                            $group.remove();
                        }else{
                            common.toast('删除失败');
                        }
                    });
                }

                return false;
            }


            function cloneHistoryItem() {
                var $item = $repeatHistoryItem.clone();
                $item.show();
                $item.attr('id','');
                return $item;
            }

            function cloneOngoingItem(){
                var $item = $repeatOngoingItem.clone();
                $item.show();
                $item.attr('id','');
                return $item;
            }
        }());
    </script>
</div>